const fs = require('fs')
const Path = require('path')
const crypto = require('crypto')

const dir1= process.argv[2] || '/Users/liuzy/Downloads/1月16日个人使用efi/CLOVER'
const dir2= process.argv[3] || '/Users/liuzy/Downloads/1月17日个人使用efi/CLOVER'

const files = fs.readdirSync(dir1)

const info1 = scan(dir1)
console.log(`dir1 ${Object.keys(info1).length} files`)
const info2 = scan(dir2)
console.log(`dir2 ${Object.keys(info2).length} files`)

// 遍历右边的文件
for (let i in info2) {
    const f2 = info2[i]
    // 看左边有没有
    let has = false, eq = false
    for (let j in info1) {
        const f1 = info1[j]
        if (f1.path == f2.path) {
            has = true
            if (f1.hash() == f2.hash()) {
                eq = true
            }
            break
        }
    }
    if (!has) {
        console.log(`\u001b[32m++\u001b[39m ${f2.path}`) // 绿色新增
    } else if (has && !eq) {
        console.log(`\u001b[34m-+\u001b[39m ${f2.path}`) // 蓝色修改
    } else {
        // console.log(`\u001b[34m--\u001b[39m ${f2.path}`) // 红色删除
    }
}

function scan(dir) {
    const info = {}
    scanDir(dir, dir, info)
    return info
}

function scanDir(dir, rootDir, info) {
    if (fs.existsSync(dir)) {
        const files = fs.readdirSync(dir)
        for (let i = 0; i < files.length; i++) {
            const name = files[i]
            const file = Path.join(dir, name) // 绝对路径
            if (name.startsWith('.')) {
                continue
            } if (fs.statSync(file).isDirectory()) {
                scanDir(file, rootDir, info)
            } else {
                const path = file.substring(rootDir.length + 1) // 相对路径
                info[path] = { file: file, path: path, hash: function() {
                    return this.md5 || (this.md5 = fileMD5(this.file))
                }}
            }
        }
    }
}

function fileMD5(path) {
    if (!fs.existsSync(path))
        return ''
    return crypto.createHash('md5').update(fs.readFileSync(path)).digest('hex')
}